<template>
  <div style="min-height: 70vh">
    <div class="mb8" style="display: flex;align-items: center;justify-content: space-between;">
      <div style="display: flex;align-items: center;font-size: 14px" v-if="activeIndex != '4'">
        <div style="margin-right: 30px;display: flex;align-items: center;">
          <span style="margin-right: 10px;">启用平台广告</span>
          <el-switch active-color="#00E266" v-model="content.openPlatform" @change="handleAdvertChange"></el-switch>
        </div>
        <div style="display: flex;align-items: center;">
          <span style="margin-right: 10px;">启用第三方广告</span>
          <el-switch active-color="#00E266" v-model="content.openThree" @change="handleAdvertChange"></el-switch>
        </div>
      </div>
      <div>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >添加</el-button>
        <el-button
          type="default"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除</el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" sortable />
      <el-table-column label="图片" align="center" prop="pic">
        <template slot-scope="scope" v-if="scope.row.pic">
          <el-image
            style="width: 80px; height: 80px"
            :src="scope.row.pic"
            fit="cover"
            :preview-src-list="[scope.row.pic]"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" v-if="activeIndex === '4'" />
      <el-table-column label="链接方式" align="center" prop="urlStyle" :key="Math.random()+'urlStyle'">
        <template slot-scope="scope">
          <span>{{ scope.row.urlStyle === 1 ? '内部页面' : '外部链接' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="链接地址" align="center" prop="url" />
      <el-table-column label="停留秒数" align="center" prop="staySecondsDesc" />
      <el-table-column label="是否跳转" align="center" prop="jump" :key="Math.random()+'jump'">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.jump" active-color="#00E266" @change="handleSwitchChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" align="center" prop="show" :key="Math.random()+'show'">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.show" active-color="#00E266" @change="handleSwitchChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="显示页面" align="center" prop="showPageDesc" v-if="activeIndex === '4'" />
      <el-table-column label="创建日期" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改启动页对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="图片：" prop="pic">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.pic" :src="form.pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题" prop="title" v-if="activeIndex === '4'">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="是否跳转" prop="jump">
          <el-switch v-model="form.jump" active-color="#00E266"></el-switch>
        </el-form-item>
        <el-form-item label="是否显示" prop="show">
          <el-switch v-model="form.show" active-color="#00E266"></el-switch>
        </el-form-item>
        <el-form-item label="显示页面" prop="showPage" v-if="activeIndex === '4'">
          <el-radio-group v-model="form.showPage">
            <el-radio :label="1">首页</el-radio>
            <el-radio :label="2">模板</el-radio>
            <el-radio :label="3">作品</el-radio>
            <el-radio :label="4">我的</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="停留秒数：" prop="staySeconds">
          <el-input v-model="form.staySeconds" placeholder="请输入停留秒数">
            <template slot="append">s</template>
          </el-input>
        </el-form-item>
        <el-form-item label="链接方式：" prop="urlStyle">
          <el-radio-group v-model="form.urlStyle">
            <el-radio :label="1">内部页面</el-radio>
            <el-radio :label="2">外部链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="链接目标：">
          <el-input v-model="form.url" placeholder="请输入地址" v-if="form.urlStyle === 2" />
          <el-cascader
            ref="cascader"
            v-model="urlValue"
            :options="urlOptions"
            :props="{ expandTrigger: 'hover', label: 'name', value: 'url', children: 'urlGoal' }"
            @change="handleChange"
            v-else></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getAdvertList, saveAdvertInfo, removeAdvertInfo, getGoalUrlInfo, getAdvertSetInfo, saveAdvertSetInfo } from "@/api/shuiyin/shuiyin";

  export default {
    name: "OtherManage",
    props: {
      activeIndex: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        // 上传地址
        uploadAction: process.env.VUE_APP_BASE_API + "/common/ossUpload",
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 租户管理表格数据
        list: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          advertisingType: null,
          pageNum: 1,
          pageSize: 10,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            { required: true, message: "会员名称不能为空", trigger: "blur" }
          ],
        },
        // 链接地址集合数据
        urlOptions: [],
        urlValue: [],
        content: {},
      };
    },
    created() {
      this.getList();
    },
    watch: {
      activeIndex: {
        handler(val) {
          console.log(val)
          if (val && val != this.queryParams.advertisingType) {
            this.getList();

            this.getSetInfo();
          }
        },
        immediate: true
      }
    },
    methods: {
      /** 查询租户管理列表 */
      getList() {
        this.loading = true;
        this.queryParams.advertisingType = Number(this.activeIndex);
        getAdvertList(this.queryParams).then(response => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getSetInfo() {
        getAdvertSetInfo({ advertisingType: Number(this.activeIndex) }).then(response => {
          if (response.data) {
            this.content = response.data;
            this.content.advertisingType = Number(this.activeIndex);
          } else {
            this.content = {
              openPlatform: false,
              openThree: false
            }
          }
        })
      },
      handleAdvertChange() {
        saveAdvertSetInfo(this.content).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getSetInfo();
          this.getList();
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          advertisingType: this.activeIndex,
          title: '',
          jump: false,
          show: false,
          pic: '',
          showPage: null,
          staySeconds: null,
          url: null,
          urlStyle: 1
        };
        this.resetForm("form");
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.urlValue = [];
        this.getInnerUrl();
        this.open = true;
        this.title = "添加";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        this.getInnerUrl();
        this.form = JSON.parse(JSON.stringify(row));
        if (this.form.url === '会员中心') {
          this.urlValue = [this.form.url]
        } else {
          this.urlValue = [null, this.form.url]
        }
        if(row.urlStyle === 3) {
          this.form.urlStyle = 1;
        }
        this.open = true;
        this.title = "修改";
      },
      handleSwitchChange(row) {
        let obj = JSON.parse(JSON.stringify(row));
        saveAdvertInfo(obj).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
        });
      },
      getInnerUrl() {
        getGoalUrlInfo().then(response => {
          this.urlOptions = response.data;
        })
      },
      // 链接地址选择事件
      handleChange(event) {
        console.log(event)
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图标大小不能超过 2MB!');
        }
        return isLt2M;
      },
      handleAvatarSuccess(res, file) {
        this.form.pic = res.data;
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            let obj = JSON.parse(JSON.stringify(this.form))

            const node = this.$refs.cascader.getCheckedNodes(true);
            if (this.form.urlStyle === 1 && node.length && node[0]) {
              obj.urlStyle = node[0].data.urlStyle
            }
            if (this.form.urlStyle === 1) {
              obj.url = this.getUrl(this.urlValue)
            }
            if (obj.id != null) {
              saveAdvertInfo(obj).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              delete obj.id;
              saveAdvertInfo(obj).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
          return removeAdvertInfo(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      getUrl(array) {
        let url = '';
        if (array.length === 0) {
          url = '';
        } else if (array.length === 1) {
          url = array[0]
        } else if (array.length === 2) {
          url = array[1]
        }
        return url
      }
    }
  };
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
</style>
